package cn.iocoder.yudao.module.infrastructure.notify.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.infrastructure.notify.controller.app.vo.AppNotifyMessagePageReqVO;
import cn.iocoder.yudao.module.infrastructure.notify.controller.app.vo.AppNotifyMessageRespVO;
import cn.iocoder.yudao.module.infrastructure.notify.dal.dataobject.NotifyMessageDO;
import cn.iocoder.yudao.module.infrastructure.notify.dal.dataobject.NotifyTemplateDO;
import cn.iocoder.yudao.module.infrastructure.notify.dal.mysql.NotifyMessageMapper;
import cn.iocoder.yudao.module.infrastructure.notify.dal.mysql.NotifyTemplateMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 App - 站内信") // FIXME 新增
@RestController
@RequestMapping("/system/notify-message")
@Validated
@Slf4j
public class AppNotifyMessageController {

    @Resource
    private NotifyMessageMapper notifyMessageMapper;
    @Resource
    private NotifyTemplateMapper notifyTemplateMapper;

    @GetMapping("/my-page")
    @Operation(summary = "获得我的站内信分页")
    public CommonResult<PageResult<AppNotifyMessageRespVO>> getMyMyNotifyMessagePage(@Valid AppNotifyMessagePageReqVO reqVO) {
        PageResult<NotifyMessageDO> pageResult = notifyMessageMapper.selectPage(reqVO, new CoreLambdaQueryWrapper<NotifyMessageDO>()
                .eqIfPresent(NotifyMessageDO::getReadStatus, reqVO.getReadStatus())
                .eq(NotifyMessageDO::getUserId, getLoginUserId())
                .eq(NotifyMessageDO::getUserType, UserTypeEnum.MEMBER.getValue())
                .orderByDesc(NotifyMessageDO::getId));
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        PageResult<AppNotifyMessageRespVO> data = BeanUtils.toBean(pageResult, AppNotifyMessageRespVO.class);
        toCommonResult(data.getList());
        return success(data);
    }

    private void toCommonResult(List<AppNotifyMessageRespVO> list) {
        Set<Long> templateIds = convertSet(list, AppNotifyMessageRespVO::getTemplateId);
        List<NotifyTemplateDO> notifyTemplateDOS = notifyTemplateMapper.selectByIds(templateIds);
        Map<Long, String> templateNameMap = notifyTemplateDOS.stream().collect(Collectors.toMap(NotifyTemplateDO::getId, NotifyTemplateDO::getName));
        list.forEach(item -> item.setTemplateName(templateNameMap.get(item.getTemplateId())));
    }

    @PostMapping("/update-read")
    @Operation(summary = "标记站内信为已读")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    public CommonResult<Boolean> updateNotifyMessageRead(@RequestParam("ids") List<Long> ids) {
        notifyMessageMapper.updateListRead(ids, getLoginUserId(), UserTypeEnum.MEMBER.getValue());
        return success(Boolean.TRUE);
    }

    @PostMapping("/update-all-read")
    @Operation(summary = "标记所有站内信为已读")
    public CommonResult<Boolean> updateAllNotifyMessageRead() {
        notifyMessageMapper.updateListRead(getLoginUserId(), UserTypeEnum.MEMBER.getValue());
        return success(Boolean.TRUE);
    }

    @GetMapping("/get-unread-list")
    @Operation(summary = "获取当前用户的最新站内信列表，默认 10 条")
    @Parameter(name = "size", description = "10")
    public CommonResult<List<AppNotifyMessageRespVO>> getUnreadNotifyMessageList(
            @RequestParam(name = "size", defaultValue = "10") Integer size) {
        List<NotifyMessageDO> list = notifyMessageMapper.selectUnreadListByUserIdAndUserType(
                getLoginUserId(), UserTypeEnum.MEMBER.getValue(), size);
        if (CollUtil.isEmpty(list)) {
            return success(Collections.emptyList());
        }
        List<AppNotifyMessageRespVO> data = BeanUtils.toBean(list, AppNotifyMessageRespVO.class);
        toCommonResult(data);
        return success(data);
    }

    @GetMapping("/get-unread-count") // TODO 建议改用SSE(Server-Sent Events)或WebSocket，而不是定时轮询
    @Operation(summary = "获得当前用户的未读站内信数量")
    public CommonResult<Integer> getUnreadNotifyMessageCount() {
        try {
            Long count = notifyMessageMapper.selectUnreadCountByUserIdAndUserType(
                    getLoginUserId(), UserTypeEnum.MEMBER.getValue());
            return success(Math.toIntExact(count));
        } catch (Exception e) {
            log.error("[getUnreadNotifyMessageCount][执行异常]", e);
            return success(0);
        }
    }

}
